package com.zc.gateway.infra.service;

import com.zc.commons.auth.dto.UrlPattenRoleDto;
import com.zc.commons.auth.pojo.SystemRole;
import com.zc.commons.auth.pojo.UrlPattenRoleCollect;
import com.zc.commons.auth.service.PattenAndRoleCacheService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.PathMatcher;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * url和角色匹配缓存service
 */
@Service
@Slf4j
public class PattenRoleMemoryCacheService implements PattenAndRoleCacheService {

    private static final String NAME_SPACE = "com.zc.gateway.infra.service.PattenRoleMemoryCacheService.";
    private UrlPattenRoleCollect urlPattenRoleCollect;

    @Autowired
    private PathMatcher pathMatcher;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;


    @Override
    public Set<String> getPattenRoles(String url) {
        Map<String, Set<String>> roleMap = this.urlPattenRoleCollect.getUrlRoleMap();
        for (Map.Entry<String, Set<String>> entry : roleMap.entrySet()) {
            if (pathMatcher.match(entry.getKey(), url)) {
                return entry.getValue();
            }
        }
        return null;
    }


    @PostConstruct
    public void loadPattenRoleCollect() {
        List<UrlPattenRoleDto> list = sqlSessionTemplate.selectList(NAME_SPACE + "queryPattenAndRole");
        Map<String, Set<String>> collect = list.stream()
                .collect(Collectors.groupingBy(UrlPattenRoleDto::getUrlPatten,
                        Collectors.mapping(SystemRole::getRoleCode, Collectors.toSet())));
        this.urlPattenRoleCollect = new UrlPattenRoleCollect();
        this.urlPattenRoleCollect.setUrlRoleMap(collect);
        log.info("角色接口权限数据内存缓存加载完成！");
    }


}
